using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Markup;
using System.Windows.Xps.Packaging;
using Common;
using MainView.MainControls.Chart;
using Microsoft.Win32;
using Report;
using SExperiment;
using SSettings;
using SWellPlate;

namespace MainView.Windows
{
	public partial class ExperimentPetientReportWindow : Window, IComponentConnector
	{
		private BaseCurveChart _Chart;

		private Experiment _Experiment;

		private List<List<Sample>> _ListSamples = new List<List<Sample>>();

		private IList<ChartData> Targets;

		private List<TemplateFile> _Files = new List<TemplateFile>();

		private int _Index;

		private ProjectReportSetting prSetting = ConfigSettings.GetInstance().ProjectReportSetting;

		private BackgroundWorker ExportAllWorker;

		private bool isPdf;

		private StringBuilder msg = new StringBuilder();

		private string m_Dir;

		public ExperimentPetientReportWindow(Experiment experiment, BaseCurveChart Chart, List<Well> wells)
		{
			InitializeComponent();
			if (experiment == null || wells == null)
			{
				throw new ArgumentNullException();
			}
			_Experiment = experiment;
			List<Sample> list = (from s in wells
				where s.Sample != null
				select s.Sample).Distinct().ToList();
			foreach (Sample sample in list)
			{
				List<Sample> list2 = null;
				if (string.IsNullOrEmpty(sample.PatientInfo.ID))
				{
					list2 = new List<Sample>();
					_ListSamples.Add(list2);
				}
				else
				{
					list2 = _ListSamples.Where((List<Sample> s) => s[0].PatientInfo.ID == sample.PatientInfo.ID).FirstOrDefault();
					if (list2 == null || list2.Count == 0)
					{
						list2 = new List<Sample>();
						_ListSamples.Add(list2);
					}
					else if (prSetting.GetProjectReport(list2[0].Project.BasicInfo.Name) != prSetting.GetProjectReport(sample.Project.BasicInfo.Name))
					{
						list2 = new List<Sample>();
						_ListSamples.Add(list2);
					}
				}
				list2.Add(sample);
			}
			if (_ListSamples.Count != 0)
			{
				if (Chart is AMPCurveChart)
				{
					_Chart = new AMPCurveChart();
				}
				else if (Chart is RawCurveChart)
				{
					_Chart = new RawCurveChart();
				}
				else if (Chart is RawMeltCurveChart)
				{
					_Chart = new RawMeltCurveChart();
				}
				else if (Chart is PeekCurveChart)
				{
					_Chart = new PeekCurveChart();
				}
				else if (Chart is XCurveChart)
				{
					_Chart = new XCurveChart();
				}
				else if (Chart is NormalizationPeakCurveChart)
				{
					_Chart = new NormalizationPeakCurveChart();
				}
				else if (Chart is NormalCurveChart)
				{
					_Chart = new NormalCurveChart();
				}
				else if (Chart is ShiftCurveChart)
				{
					_Chart = new ShiftCurveChart();
				}
				else if (Chart is DifferenceCurveChart)
				{
					_Chart = new DifferenceCurveChart();
				}
				if (_Chart != null)
				{
					_Chart.PrintMode = true;
					_Chart.Subset = Chart.Subset;
					_Chart.ColorMode = Chart.ColorMode;
					_Chart.ThresholdVisible = Chart.ThresholdVisible;
					_Chart.MinX = Chart.MinX;
					_Chart.MaxX = Chart.MaxX;
					_Chart.MinY = Chart.MinY;
					_Chart.MaxY = Chart.MaxY;
					_Chart.TitleX = Chart.TitleX;
					_Chart.TitleY = Chart.TitleY;
					_Chart.TitleXFormat = Chart.TitleXFormat;
					_Chart.TitleYFormat = Chart.TitleYFormat;
					_Chart.UltraChart.Chart.Dock = DockStyle.None;
					_Chart.UltraChart.Chart.Width = 500;
					_Chart.UltraChart.Chart.Height = 350;
					_Chart.DisplayAllSeries = true;
					Targets = Chart.Targets;
				}
				List<IDocumentPaginatorSource> list3 = new List<IDocumentPaginatorSource>();
				List<string> list4 = new List<string>();
				List<string> list5 = new List<string>();
				for (int i = 0; i < _ListSamples.Count; i++)
				{
					list3.Add(null);
					list4.Add(null);
					list5.Add(null);
				}
				_Files.Add(new TemplateFile
				{
					Documents = list3,
					XPSFiles = list4,
					WordPath = list5
				});
				listBoxTemplateFile.ItemsSource = _Files;
				listBoxTemplateFile.SelectedIndex = 0;
				RefreshButtonStatus();
			}
		}

		private string CreateSampleChart(List<Sample> samples, double width, double height, List<int> TubeNoList, List<int> ChannelNoList)
		{
			string path = string.Empty;
			if (_Chart != null && Targets != null)
			{
				base.Dispatcher.Invoke((Action)delegate
				{
					List<ChartData> list = Targets.Where((ChartData s) => samples.Contains(s.WellCell.Well.Sample)).ToList();
					List<ChartData> list2 = new List<ChartData>();
					for (int i = 0; i < TubeNoList.Count; i++)
					{
						List<ChartData> list3 = new List<ChartData>();
						int tubeNo = TubeNoList[i];
						if (tubeNo > 0)
						{
							list3 = list.Where((ChartData s) => s.WellCell.Well.MultiTubeID == tubeNo).ToList();
						}
						int ChannelNo = ChannelNoList[i];
						if (ChannelNo > 0)
						{
							list3 = list3.Where((ChartData s) => s.SampleTargetItem.ChannelNo == ChannelNo).ToList();
						}
						list2.AddRange(list3);
					}
					list2.Distinct();
					if (list2.Count == 0)
					{
						list2.AddRange(list);
					}
					_Chart.UltraChart.Chart.Width = (int)width;
					_Chart.UltraChart.Chart.Height = (int)height;
					_Chart.Targets = list2;
					_Chart.RefreshSeries();
					path = Utility.GetSystemTempFile();
					_Chart.UltraChart.SaveAsImage(path);
				}, new object[0]);
			}
			return path;
		}

		private void RefreshButtonStatus()
		{
			btnPrevious.IsEnabled = ((_Index != 0) ? true : false);
			btnNext.IsEnabled = ((_Index != _ListSamples.Count - 1) ? true : false);
			bntPrintAll.IsEnabled = ((_ListSamples.Count > 1) ? true : false);
			btnExportAll.IsEnabled = ((_ListSamples.Count > 1) ? true : false);
		}

		private void RefreshDocument()
		{
			RefreshDocument(_Index);
			if (listBoxTemplateFile.SelectedItem == null)
			{
				return;
			}
			TemplateFile templateFile = listBoxTemplateFile.SelectedItem as TemplateFile;
			documentViewer.Document = templateFile.Documents[_Index];
			tbError.Text = null;
			if (templateFile.Documents[_Index] == null)
			{
				string name = _ListSamples[_Index][0].Project.BasicInfo.Name;
				string projectReport = prSetting.GetProjectReport(name);
				if (!File.Exists(Utility.GetReportTemplatePath() + projectReport))
				{
					tbError.Text = string.Format(Utility.GetMessage("msg_notfound_project_report"), name, projectReport);
				}
			}
			tbError.Visibility = (string.IsNullOrEmpty(tbError.Text) ? Visibility.Collapsed : Visibility.Visible);
		}

		private void worker_DoWorkCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
		}

		private void worker_DoWork(object sender, DoWorkEventArgs e)
		{
			BackgroundWorker backgroundWorker = sender as BackgroundWorker;
			TemplateFile templateFile = e.Argument as TemplateFile;
			if (backgroundWorker == null || templateFile == null)
			{
				return;
			}
			Thread.Sleep(100);
			for (int i = 0; i < templateFile.Documents.Count; i++)
			{
				if (backgroundWorker.CancellationPending)
				{
					break;
				}
				Utility.DoEvents();
				if (string.IsNullOrEmpty(templateFile.XPSFiles[i]))
				{
					string outWordPath = string.Empty;
					templateFile.XPSFiles[i] = ExportReport.CreateSampleResultXPSDocument(_Experiment, _ListSamples[i], Utility.GetReportTemplatePath() + prSetting.GetProjectReport(_ListSamples[i][0].Project.BasicInfo.Name), CreateSampleChart, out outWordPath);
					templateFile.WordPath[i] = outWordPath;
				}
			}
		}

		private void listBoxTemplateFile_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			RefreshDocument();
			base.Dispatcher.BeginInvoke((Action)delegate
			{
				if (listBoxTemplateFile.SelectedItem is TemplateFile)
				{
					TemplateFile templateFile = listBoxTemplateFile.SelectedItem as TemplateFile;
					foreach (TemplateFile file in _Files)
					{
						if (file != templateFile && file.BackgroundWorker != null && file.BackgroundWorker.IsBusy)
						{
							file.BackgroundWorker.CancelAsync();
						}
					}
					if (templateFile.BackgroundWorker == null)
					{
						templateFile.BackgroundWorker = new BackgroundWorker();
						templateFile.BackgroundWorker.WorkerSupportsCancellation = true;
						templateFile.BackgroundWorker.DoWork += worker_DoWork;
						templateFile.BackgroundWorker.RunWorkerCompleted += worker_DoWorkCompleted;
					}
					if (templateFile.BackgroundWorker != null && !templateFile.BackgroundWorker.IsBusy)
					{
						templateFile.BackgroundWorker.RunWorkerAsync(listBoxTemplateFile.SelectedItem);
					}
				}
			});
		}

		private void RefreshDocument(int idx)
		{
			if (listBoxTemplateFile.SelectedItem == null)
			{
				return;
			}
			TemplateFile templateFile = listBoxTemplateFile.SelectedItem as TemplateFile;
			if (idx < templateFile.Documents.Count && templateFile.Documents[idx] == null)
			{
				if (string.IsNullOrEmpty(templateFile.XPSFiles[idx]))
				{
					string outWordPath = string.Empty;
					templateFile.XPSFiles[idx] = ExportReport.CreateSampleResultXPSDocument(_Experiment, _ListSamples[idx], Utility.GetReportTemplatePath() + prSetting.GetProjectReport(_ListSamples[idx][0].Project.BasicInfo.Name), CreateSampleChart, out outWordPath);
					templateFile.WordPath[idx] = outWordPath;
				}
				if (!string.IsNullOrEmpty(templateFile.XPSFiles[idx]) && File.Exists(templateFile.XPSFiles[idx]))
				{
					XpsDocument xpsDocument = new XpsDocument(templateFile.XPSFiles[idx], FileAccess.Read);
					IDocumentPaginatorSource fixedDocumentSequence = xpsDocument.GetFixedDocumentSequence();
					xpsDocument.Close();
					templateFile.Documents[idx] = fixedDocumentSequence;
					tbError.Text = null;
				}
				else
				{
					tbError.Text = "Failed to load the patient report.";
				}
				tbError.Visibility = (string.IsNullOrEmpty(tbError.Text) ? Visibility.Collapsed : Visibility.Visible);
			}
		}

		private void btnPrevious_Click(object sender, RoutedEventArgs e)
		{
			_Index--;
			RefreshButtonStatus();
			RefreshDocument();
		}

		private void btnNext_Click(object sender, RoutedEventArgs e)
		{
			_Index++;
			RefreshButtonStatus();
			RefreshDocument();
		}

		private void bgExportAllWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			loading.Visibility = Visibility.Collapsed;
			base.Dispatcher.Invoke((Action)delegate
			{
				if (msg.Length > 0)
				{
					System.Windows.MessageBox.Show(msg.ToString() + Utility.GetMessage("msg_patient_report_export_failed"));
				}
				else
				{
					System.Windows.MessageBox.Show(Utility.GetMessage("msg_patient_report_export_sussess"));
				}
			}, new object[0]);
		}

		private void bgExportAllWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			base.Dispatcher.Invoke((Action)delegate
			{
			}, new object[0]);
		}

		private void bgExportAllWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			base.Dispatcher.Invoke((Action)delegate
			{
				loading.Visibility = Visibility.Visible;
			}, new object[0]);
			GetData(isPdf);
		}

		private void GetData(bool isPdf)
		{
			for (int i = 0; i < listBoxTemplateFile.Items.Count; i++)
			{
				TemplateFile templateFile = listBoxTemplateFile.Items[i] as TemplateFile;
				for (int j = 0; j < templateFile.WordPath.Count; j++)
				{
					string text = templateFile.WordPath[j];
					if (string.IsNullOrEmpty(text))
					{
						continue;
					}
					string empty = string.Empty;
					if (isPdf)
					{
						empty = m_Dir + "\\" + _ListSamples[j][0].PatientInfo.ID + "_" + _ListSamples[j][0].WellNames + ".pdf";
					}
					else
					{
						empty = _ListSamples[j][0].PatientInfo.ID + "_" + _ListSamples[j][0].WellNames + ".docx";
						empty = m_Dir + "\\" + empty;
					}
					if (File.Exists(empty) && System.Windows.MessageBox.Show(string.Format(empty + Utility.GetMessage("msg_file_exist_cover")), Utility.GetMessage("warning"), MessageBoxButton.YesNo) == MessageBoxResult.No)
					{
						return;
					}
					try
					{
						if (isPdf)
						{
							WordOperator.ExportToPDF(text, empty);
						}
						else
						{
							File.Copy(text, empty, true);
						}
					}
					catch (Exception)
					{
						msg.AppendLine(empty);
					}
				}
			}
		}

		private void ExportAllExcuted(bool ispdf)
		{
			msg.Clear();
			if (listBoxTemplateFile.Items.Count != 0)
			{
				FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
				DialogResult dialogResult = folderBrowserDialog.ShowDialog();
				if (dialogResult != System.Windows.Forms.DialogResult.Cancel)
				{
					m_Dir = folderBrowserDialog.SelectedPath.Trim();
					isPdf = ispdf;
					StopBackgroud();
					ExportAllWorker = new BackgroundWorker();
					ExportAllWorker.WorkerReportsProgress = true;
					ExportAllWorker.DoWork += bgExportAllWorker_DoWork;
					ExportAllWorker.ProgressChanged += bgExportAllWorker_ProgressChanged;
					ExportAllWorker.RunWorkerCompleted += bgExportAllWorker_RunWorkerCompleted;
					ExportAllWorker.RunWorkerAsync();
				}
			}
		}

		private void btnExportToWord_Click(object sender, RoutedEventArgs e)
		{
			if (listBoxTemplateFile.SelectedItem == null)
			{
				return;
			}
			TemplateFile templateFile = listBoxTemplateFile.SelectedItem as TemplateFile;
			string text = templateFile.WordPath[_Index];
			if (string.IsNullOrEmpty(text))
			{
				return;
			}
			Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text);
			fileNameWithoutExtension = _ListSamples[_Index][0].PatientInfo.ID;
			saveFileDialog.FileName = fileNameWithoutExtension;
			saveFileDialog.Filter = string.Format("{0}{1}|*.{2}", ".docx", Utility.GetMessage("File"), "docx");
			saveFileDialog.FilterIndex = 1;
			saveFileDialog.InitialDirectory = Utility.GetMyDocumentFolder();
			saveFileDialog.DefaultExt = "docx";
			bool? flag = saveFileDialog.ShowDialog();
			if (flag == true && flag.HasValue && (!File.Exists(saveFileDialog.FileName) || System.Windows.MessageBox.Show(string.Format(Utility.GetMessage("msg_file_exist_cover")), Utility.GetMessage("warning"), MessageBoxButton.YesNo) != MessageBoxResult.No))
			{
				try
				{
					File.Copy(text, saveFileDialog.FileName, true);
					System.Windows.MessageBox.Show(Utility.GetMessage("msg_patient_report_export_sussess"));
				}
				catch (Exception)
				{
					System.Windows.MessageBox.Show(Utility.GetMessage("msg_patient_report_export_failed"));
				}
			}
		}

		private void bgPrintAllWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			loading.Visibility = Visibility.Collapsed;
		}

		private void bgPrintAllWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			base.Dispatcher.Invoke((Action)delegate
			{
				loading.Visibility = Visibility.Visible;
				System.Windows.Controls.PrintDialog printDialog = new System.Windows.Controls.PrintDialog();
				bool? flag = printDialog.ShowDialog();
				if (flag == true && flag.HasValue && listBoxTemplateFile.SelectedItem != null)
				{
					TemplateFile templateFile = listBoxTemplateFile.SelectedItem as TemplateFile;
					for (int i = 0; i < templateFile.Documents.Count; i++)
					{
						RefreshDocument(i);
						if (templateFile.Documents[i] != null && templateFile.Documents[i].DocumentPaginator != null)
						{
							printDialog.PrintDocument(templateFile.Documents[i].DocumentPaginator, "Print");
						}
					}
				}
			}, new object[0]);
		}

		private void bntPrintAll_Click(object sender, RoutedEventArgs e)
		{
			StopBackgroud();
			ExportAllWorker = new BackgroundWorker();
			ExportAllWorker.WorkerReportsProgress = true;
			ExportAllWorker.DoWork += bgPrintAllWorker_DoWork;
			ExportAllWorker.RunWorkerCompleted += bgPrintAllWorker_RunWorkerCompleted;
			ExportAllWorker.RunWorkerAsync();
		}

		private void bntPrintSelect_Click(object sender, RoutedEventArgs e)
		{
			documentViewer.Print();
		}

		private void StopBackgroud()
		{
			foreach (TemplateFile file in _Files)
			{
				if (file.BackgroundWorker != null && file.BackgroundWorker.IsBusy)
				{
					file.BackgroundWorker.CancelAsync();
				}
			}
		}

		private void Root_Closed(object sender, EventArgs e)
		{
			StopBackgroud();
		}

		private void btnExportAllWord_Click(object sender, RoutedEventArgs e)
		{
			ExportAllExcuted(false);
		}

		private void btnExportAllPdf_Click(object sender, RoutedEventArgs e)
		{
			ExportAllExcuted(true);
		}

		private void btnExportAll_Click(object sender, RoutedEventArgs e)
		{
			menu.IsOpen = true;
		}
	}
}
